<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { QForm, QTable, type FormItemRows, type QPaginationProps, type TableColums } from '@meetjs/element-plus-kit'
import { toViewModel, toViewModelAsync, type AthleteViewModel } from '@/api/athlete/transformer'
import type { AttachmentInfo } from '@/api/files/types'
import { getAthleteByIdApi } from '@/api/athlete'
import { usePreview } from '@/composables/usePreview'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAthleteListStore } from '@/store/athlete/athleteList'
import { useFirstRegistrationListStore } from '@/store/athlete/firstRegistrationList'
import { useYearlyConfirmListStore } from '@/store/athlete/yearlyConfirmList'
import { useProjectChangeListStore } from '@/store/athlete/projectChangeList'
import { useOrgChangeListStore } from '@/store/athlete/orgChangeList'
import { registerInfoOptions, basicInfoOptions } from './formConfig'
import registerTime from '@/assets/athlete/detail/register-time.svg?url'
import idCard from '@/assets/athlete/detail/id.svg?url'
import avatarIcon from '@/assets/athlete/detail/avatarIcon.svg?url'
import camera from '@/assets/athlete/detail/camera.svg?url'
import idCert from '@/assets/athlete/detail/idCert.svg?url'
import levelCert from '@/assets/athlete/detail/levelCert.svg?url'
import healthCert from '@/assets/athlete/detail/healthCert.svg?url'
import eduCert from '@/assets/athlete/detail/eduCert.svg?url'
import ticketSuccess from '@/assets/athlete/detail/ticketSuccess.svg?url'
import downloadIcon from '@/assets/athlete/detail/download.svg?url'
import fileIcon from '@/assets/athlete/detail/file.png?url'
import eyeIcon from '@/assets/athlete/icons/eye.svg?url'

import TraningHistory from './components/TrainingHistory/index.vue'
import { AthleteLevel } from './components/AthleteLevel'
import { RewardRecord } from './components/RewardRecord'
import { SeedSelection } from './components/SeedSelection'
import TeamExperience from './components/TeamExperience/index.vue'
import { CompetitionRecord } from './components/CompetitionRecord'
import { ChangeHistory } from './components/ChangeHistory'

// 路由参数
const route = useRoute()
const router = useRouter()
const athleteStore = useAthleteListStore()

//  各种列表Store
const firstRegistrationStore = useFirstRegistrationListStore()
const yearlyConfirmStore = useYearlyConfirmListStore()
const projectChangeStore = useProjectChangeListStore()
const orgChangeStore = useOrgChangeListStore()

//  根据路由参数或来源判断使用哪个Store
const getCurrentStore = () => {
	// 优先从 query 参数中获取来源标识
	const from = route.query.from as string
	if (from) {
		switch (from) {
			case 'firstRegistration':
				return firstRegistrationStore
			case 'yearlyConfirm':
				return yearlyConfirmStore
			case 'projectChange':
				return projectChangeStore
			case 'orgChange':
				return orgChangeStore
			default:
				break
		}
	}

	// 如果没有 from 参数，尝试从 meta 信息获取
	const listSource = route.meta?.listSource as string
	if (listSource) {
		switch (listSource) {
			case 'firstRegistration':
				return firstRegistrationStore
			case 'yearlyConfirm':
				return yearlyConfirmStore
			case 'projectChange':
				return projectChangeStore
			case 'orgChange':
				return orgChangeStore
			default:
				break
		}
	}

	// 默认使用主列表Store（需要包装以提供兼容接口）
	return {
		...athleteStore,
		get idList() {
			// 将 athleteStore.list 中的 id 提取为数组
			return athleteStore.list.map(item => item.id).filter(Boolean)
		},
		get hasPrev() {
			return athleteStore.hasPrev
		},
		get hasNext() {
			return athleteStore.hasNext
		},
		get currentPosition() {
			return athleteStore.currentPosition
		},
		setCurrentById: athleteStore.setCurrentById.bind(athleteStore),
		gotoPrev: athleteStore.gotoPrev.bind(athleteStore),
		gotoNext: athleteStore.gotoNext.bind(athleteStore)
	}
}

//  Store通用接口类型
type NavigationStore = {
	// 新的Store结构使用list，老的使用idList
	list?: any[]
	idList?: (string | number)[]
	pagination: {
		currentPage: number
		pageSize: number
		total: number
	}
	hasPrev: boolean
	hasNext: boolean
	currentPosition: number
	setCurrentById: (id: string | number) => boolean
	gotoPrev: () => Promise<string | number | null>
	gotoNext: () => Promise<string | number | null>
}

//  获取当前Store实例
const currentStore = getCurrentStore() as NavigationStore

// 运动员详情数据
const athleteDetail = ref<AthleteViewModel>({})
const loading = ref(false)

// 额外数据（训练、比赛、奖励等）
const extraData = ref<{
	trains: any[]
	teams: any[]
	races: any[]
	rewards: any[]
	levels: any[]
	seeds: any[]
	changes: any[]
}>({
	trains: [],
	teams: [],
	races: [],
	rewards: [],
	levels: [],
	seeds: [],
	changes: []
})

// 加载详情数据
const loadDetail = async (id: number | string) => {
	try {
		loading.value = true
		const res = await getAthleteByIdApi(id)

		// 提取 info 字段作为运动员基本信息
		if (res.data?.info) {
			//  使用异步转换，自动加载所有运动员的照片文件信息
			athleteDetail.value = await toViewModelAsync(res.data.info)

			// 保存额外数据
			extraData.value = {
				trains: res.data.trains || [],
				teams: res.data.teams || [],
				races: res.data.races || [],
				rewards: res.data.rewards || [],
				levels: res.data.levels || [],
				seeds: res.data.seeds || [],
				changes: res.data.changes || []
			}

			//  如果 Store 中没有这条数据，设置一下
			if (!currentStore.setCurrentById(id)) {
				// 可能是直接访问的链接，Store 中没有数据
				console.warn('直接访问详情页，Store 中无列表数据')
			}

			console.log('运动员详情:', athleteDetail.value)
			console.log('额外数据:', extraData.value)
		} else {
			console.error('接口返回数据格式错误')
		}
	} catch (error) {
		console.error('加载运动员详情失败:', error)
	} finally {
		loading.value = false
	}
}

//  上一条
const handlePrev = async () => {
	if (!currentStore.hasPrev) {
		ElMessage.warning('已经是第一条了')
		return
	}

	try {
		loading.value = true
		const prevId = await currentStore.gotoPrev()

		if (prevId) {
			// 更新路由，保持来源信息
			const query: any = { id: prevId }
			if (route.query.from) query.from = route.query.from

			router.replace({
				path: '/athleteFirst/detail',
				query
			})

			// 加载详情
			await loadDetail(prevId)
		}
	} catch (error) {
		ElMessage.error('加载上一条失败')
		console.error(error)
	} finally {
		loading.value = false
	}
}

//  下一条
const handleNext = async () => {
	if (!currentStore.hasNext) {
		ElMessage.warning('已经是最后一条了')
		return
	}

	try {
		loading.value = true
		const nextId = await currentStore.gotoNext()

		if (nextId) {
			// 更新路由，保持来源信息
			const query: any = { id: nextId }
			if (route.query.from) query.from = route.query.from

			router.replace({
				path: '/athleteFirst/detail',
				query
			})

			// 加载详情
			await loadDetail(nextId)
		}
	} catch (error) {
		ElMessage.error('加载下一条失败')
		console.error(error)
	} finally {
		loading.value = false
	}
}

//  返回列表
const handleBack = () => {
	router.back()
}

//  键盘快捷键支持（左右箭头翻页）
const handleKeydown = (e: KeyboardEvent) => {
	// 避免在输入框中触发
	const target = e.target as HTMLElement
	if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') {
		return
	}

	if (e.key === 'ArrowLeft' && !loading.value) {
		handlePrev()
	} else if (e.key === 'ArrowRight' && !loading.value) {
		handleNext()
	}
}

// 初始化加载
onMounted(() => {
	const id = route.query.id
	if (id) {
		loadDetail(id as string)
	}

	//  添加键盘事件监听
	// window.addEventListener('keydown', handleKeydown)
})

//  组件卸载时移除监听器
onUnmounted(() => {
	// window.removeEventListener('keydown', handleKeydown)
})

// 审核记录数据
const auditRecords = ref([
	{
		id: 1,
		title: '注册审核通过',
		operator: '审核员A',
		description: '所有材料齐全，信息核实无误',
		time: '2024-09-09'
	},
	{
		id: 2,
		title: '身份验证通过',
		operator: '审核员A',
		description: '人脸识别和提纹验证通过',
		time: '2024-09-09'
	},
	{
		id: 3,
		title: '提交注册申请',
		operator: '审核员A',
		description: '运动员本人注册申请',
		time: '2024-09-09'
	}
])

// 图片预览 hooks
const { preview, previewList } = usePreview()

//  证件材料项类型定义
interface CertItem {
	id: string
	title: string
	icon: string
	verified: boolean
	date: string
	file: AttachmentInfo
}

//  证件材料数据（从 athleteDetail 动态生成）
const certList = computed(() => {
	const list: CertItem[] = []

	// 身份证正面
	if (athleteDetail.value.identityFrontFile) {
		list.push({
			id: 'identityFront',
			title: '身份证正面',
			icon: idCert,
			verified: true,
			date: athleteDetail.value.identityFrontFile.createTime || '',
			file: athleteDetail.value.identityFrontFile
		})
	}

	// 身份证反面
	if (athleteDetail.value.identityBackFile) {
		list.push({
			id: 'identityBack',
			title: '身份证反面',
			icon: idCert,
			verified: true,
			date: athleteDetail.value.identityBackFile.createTime || '',
			file: athleteDetail.value.identityBackFile
		})
	}

	// 运动员资格证书（支持多张）
	if (athleteDetail.value.qualificationsFile && Array.isArray(athleteDetail.value.qualificationsFile)) {
		athleteDetail.value.qualificationsFile.forEach((file, index) => {
			list.push({
				id: `qualifications-${index}`,
				title: `运动员资格证书${athleteDetail.value.qualificationsFile!.length > 1 ? ` (${index + 1})` : ''}`,
				icon: levelCert,
				verified: true,
				date: file.createTime || '',
				file: file
			})
		})
	}

	// 其他证明材料（支持多张）
	if (athleteDetail.value.otherMaterialFile && Array.isArray(athleteDetail.value.otherMaterialFile)) {
		athleteDetail.value.otherMaterialFile.forEach((file, index) => {
			list.push({
				id: `otherMaterial-${index}`,
				title: `其他证明材料${athleteDetail.value.otherMaterialFile!.length > 1 ? ` (${index + 1})` : ''}`,
				icon: eduCert,
				verified: true,
				date: file.createTime || '',
				file: file
			})
		})
	}

	return list
})

function onViewCert(id: string) {
	const cert = certList.value.find(item => item.id === id)
	if (cert?.file?.filePath) {
		//  支持多张图片预览
		const allImages = certList.value.map(item => item.file?.filePath).filter(Boolean) as string[]
		const currentIndex = certList.value.findIndex(item => item.id === id)
		previewList(allImages, currentIndex)
	} else {
		ElMessage.warning('文件不存在或无法预览')
	}
}

async function onDownloadCert(id: string) {
	const cert = certList.value.find(item => item.id === id)
	if (cert?.file?.filePath) {
		try {
			//  使用 fetch + Blob 方式强制下载，避免浏览器直接打开图片
			const response = await fetch(cert.file.filePath)
			if (!response.ok) {
				throw new Error('下载失败')
			}

			const blob = await response.blob()
			const url = window.URL.createObjectURL(blob)
			const link = document.createElement('a')
			link.href = url
			// 使用文件原名或者使用证件标题 + 扩展名
			const fileName = cert.file.fileName || `${cert.title}.${cert.file.fileType || 'jpg'}`
			link.download = fileName
			link.style.display = 'none'
			document.body.appendChild(link)
			link.click()
			// 清理
			document.body.removeChild(link)
			window.URL.revokeObjectURL(url)
			ElMessage.success('开始下载')
		} catch (error) {
			console.error('下载失败:', error)
			ElMessage.error('下载失败，请重试')
		}
	} else {
		ElMessage.warning('文件不存在或无法下载')
	}
}
</script>

<template>
	<div class="p-4 flex flex-col gap-4 bg-secondary min-h-full">
		<!--  位置信息条（有列表上下文时） -->
		<!--  增加 disableNav 判断：从项目/单位变更进入时隐藏导航条 -->
		<div
			v-if="
				!route.query.disableNav &&
				((currentStore.list && currentStore.list.length > 0) || (currentStore.idList && currentStore.idList.length > 0))
			"
			class="p-4 bg-primary rounded flex items-center justify-between"
		>
			<div class="flex items-center gap-4">
				<!--  返回按钮 -->
				<el-button @click="handleBack">
					<span>← 返回列表</span>
				</el-button>

				<div class="text-sm text-secondary">
					当前位置：第
					<span class="text-brand font-500 mx-1">{{ currentStore.currentPosition }}</span>
					/
					<span class="mx-1">{{ currentStore.pagination.total }}</span>
					条
				</div>
				<!--  进度条 -->
				<div class="w-[200px]">
					<el-progress
						:percentage="(currentStore.currentPosition / currentStore.pagination.total) * 100"
						:show-text="false"
						:stroke-width="6"
					/>
				</div>
			</div>
			<!--  上下翻页按钮 -->
			<div class="flex items-center gap-2">
				<el-button
					:disabled="!currentStore.hasPrev || loading"
					@click="handlePrev"
				>
					<span>← 上一条</span>
				</el-button>
				<el-button
					type="primary"
					:disabled="!currentStore.hasNext || loading"
					@click="handleNext"
				>
					<span>下一条 →</span>
				</el-button>
			</div>
		</div>

		<!--  简单返回条（直接访问时） -->
		<div
			v-else
			class="p-4 bg-primary rounded flex items-center justify-between"
		>
			<el-button @click="handleBack">
				<span>← 返回</span>
			</el-button>
			<div class="text-sm text-secondary">运动员详情</div>
		</div>

		<!-- 顶部信息区 -->
		<div class="p-5 flex items-center bg-primary rounded">
			<!-- 头像 -->
			<div class="relative size-[100px] mr-6">
				<img
					:src="athleteDetail.personPhotoFile?.filePath"
					class="size-full object-cover rounded-full"
					alt="avatar"
				/>
				<img
					:src="camera"
					class="size-[24px] absolute right-0 bottom-0"
					alt="camera"
				/>
			</div>
			<!-- 基本信息 -->
			<div class="flex flex-col gap-4">
				<div class="flex items-center gap-[7px]">
					<div class="text-2xl font-500 text-primary">{{ athleteDetail.athleteName }}</div>
					<div class="hidden table-tag bg-[#F7BA1E]/10 text-[#B68507]">
						{{ athleteDetail.athleteLevel }}
					</div>
				</div>
				<div class="flex items-center gap-2">
					<div class="flex items-center text-secondary text-sm font-500">
						<img
							:src="avatarIcon"
							class="size-4 mr-1"
						/>
						<!-- 性别年龄 -->
						<span>{{ athleteDetail.sexLabel }}·{{ athleteDetail.age }}岁</span>
					</div>
					<div class="flex items-center text-secondary text-sm font-500">
						<img
							:src="idCard"
							class="size-4 mr-1"
						/>
						<!-- 出身年月日 -->
						<span>{{ athleteDetail.birthday }}</span>
					</div>
					<div class="flex items-center text-secondary text-sm font-500">
						<img
							:src="registerTime"
							class="size-4 mr-1"
						/>
						<!-- 注册时间 -->
						<span>{{ athleteDetail.registerTime }}</span>
					</div>
				</div>
				<div class="flex gap-2 text-sm text-secondary">
					<div class="flex px-[10px] py-1 bg-tertiary rounded-full h-[22px] items-center">
						{{ athleteDetail.registerStatusLabel }}
					</div>
					<div class="flex px-[10px] py-1 bg-tertiary rounded-full h-[22px] items-center">
						{{ athleteDetail.registerProjectLabel }}
					</div>
				</div>
			</div>
		</div>

		<!-- 注册信息 -->
		<div class="p-5 bg-primary rounded">
			<div class="text-primary text-base mb-3 font-500">注册信息</div>
			<QForm
				v-if="athleteDetail"
				:model="athleteDetail"
				:form-options="registerInfoOptions"
				:col="24"
				:gutter="24"
				readonly
			/>
		</div>

		<!-- 基本信息 -->
		<div class="p-5 bg-primary rounded">
			<div class="text-primary text-base mb-3 font-500">基本信息</div>
			<QForm
				v-if="athleteDetail"
				:model="athleteDetail"
				:form-options="basicInfoOptions"
				:col="24"
				:gutter="24"
				readonly
			/>
		</div>

		<!-- 最近训练记录 -->
		<TraningHistory
			:athlete-id="athleteDetail.id as number"
			:data="extraData.trains"
		/>

		<!-- 集训及入队经历 -->
		<TeamExperience
			:athlete-id="athleteDetail.id as number"
			:data="extraData.teams"
		/>

		<!-- 比赛信息 -->
		<CompetitionRecord
			:athlete-id="athleteDetail.id as number"
			:data="extraData.races"
		/>

		<!-- 运动员等级 -->
		<AthleteLevel
			:athlete-id="athleteDetail.id as number"
			:data="extraData.levels"
		/>

		<!-- 奖罚情况 -->
		<RewardRecord
			:athlete-id="athleteDetail.id as number"
			:data="extraData.rewards"
		/>

		<!-- 苗子选拔标准测试 -->
		<SeedSelection
			:athlete-id="athleteDetail.id as number"
			:data="extraData.seeds"
		/>

		<!-- 变更历史 -->
		<ChangeHistory
			:athlete-id="athleteDetail.id as number"
			:data="extraData.changes"
		/>

		<!-- 证件材料 -->
		<div class="p-5 bg-primary rounded">
			<div class="text-base text-primary font-500 mb-4">证件材料</div>
			<div class="grid grid-cols-4 gap-4">
				<!-- hover box-shadow: 0px 2px 5px 0px rgba(0, 0, 0, 0.1); -->
				<div
					v-for="item in certList"
					:key="item.id"
					class="p-4 rounded border border-[#E6E9F0] bg-white hover:shadow-[0px_2px_5px_0px_rgba(0,0,0,0.1)]"
				>
					<div class="flex items-center gap-2 mb-3">
						<img
							:src="item.icon"
							class="size-6"
						/>
						<div class="text-primary font-500">{{ item.title }}</div>
						<div class="ml-1 flex items-center px-2 rounded-[2px] h-[22px] bg-[#67C23A]/10 text-[#3A7C17] text-xs">
							<img
								:src="ticketSuccess"
								class="size-3 mr-1"
							/>
							已验证
						</div>
					</div>
					<div class="text-secondary text-sm mb-4 ml-8">上传时间：{{ item.date }}</div>
					<div class="flex gap-3 ml-8">
						<el-button
							type="primary"
							@click="onViewCert(item.id)"
						>
							<img
								:src="eyeIcon"
								class="size-4 mr-1.5"
							/>
							<span>查看</span>
						</el-button>
						<el-button
							class="text-brand!"
							@click="onDownloadCert(item.id)"
						>
							<img
								:src="downloadIcon"
								class="size-4 mr-1.5"
							/>
							下载
						</el-button>
					</div>
				</div>
			</div>
		</div>

		<!-- 证件审核记录资料 -->
		<div class="p-5 bg-primary rounded">
			<div class="text-base text-primary font-500 mb-4">证件审核记录资料</div>
			<div class="flex flex-col gap-6">
				<div
					v-for="record in auditRecords"
					:key="record.id"
					class="relative"
				>
					<!-- 时间线 -->
					<div class="flex gap-4">
						<!-- 左侧图标和线 -->
						<div class="flex flex-col items-center">
							<img
								:src="fileIcon"
								class="size-6 object-fill"
							/>
							<div class="w-px bg-light flex-1 mt-2" />
						</div>
						<!-- 右侧内容 -->
						<div class="flex-1 pb-2">
							<div class="flex items-center justify-between mb-2">
								<div class="text-primary font-500">{{ record.title }}</div>
								<div class="text-secondary text-sm">{{ record.time }}</div>
							</div>
							<div class="text-secondary text-sm mb-0.5">操作人：{{ record.operator }}</div>
							<div class="text-secondary text-sm">{{ record.description }}</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>
